package com.qianxx.view.loadingview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import com.qianxx.base.R;

/**
 * Created on 16/5/20 下午1:05.
 *
 * @author binwin20
 */
public class LoadingView extends View {

    private Paint mPaint;
    private int mTickCount;
    private int mLightSpotColor = 0xff00aaff;
    private int mSpotColor = 0xff666666;
    private float mRadius = 2;
    private float mPadding = 1;

    public LoadingView(Context context) {
        this(context, null);
    }

    public LoadingView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LoadingView, 0, R.style.LoadingViewDefStyle);
        mLightSpotColor = ta.getColor(R.styleable.LoadingView_light_spot_color, mLightSpotColor);
        mSpotColor = ta.getColor(R.styleable.LoadingView_spot_color, mSpotColor);
        mRadius = ta.getDimension(R.styleable.LoadingView_spot_radius, mRadius);
        mPadding = ta.getDimension(R.styleable.LoadingView_spot_padding, mPadding);
        ta.recycle();
        initView(context);
    }

    private void initView(Context context) {
        mPaint = new Paint();
        setClickable(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mTickCount < 0)
            return;
        if (mTickCount < 2) {
            if (mTickCount == 0) {
                // 第一帧动画不显示
                mTickCount++;
                postInvalidateDelayed(1000);
                return;
            } else {
                setAlpha(1);
            }
        }
        //Log.d("bin-->", "LoadingView#onDraw(): ");
        int light = mTickCount % 3 - 1;
        for (int i = -1; i <= 1; i++) {
            mPaint.setColor(i == light ? mLightSpotColor : mSpotColor);
            float centerX = getWidth() / 2 + i * (mPadding + mRadius * 2);
            canvas.drawCircle(centerX, getHeight() / 2, mRadius, mPaint);
        }
        mTickCount++;
        postInvalidateDelayed(1000);
    }

    public void show(boolean fullScreen) {
        mTickCount = 0;
        setAlpha(0);
        postInvalidate();
        setVisibility(VISIBLE);
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) getLayoutParams();
        if (fullScreen) {
            lp.topMargin = 0;
        } else {
            lp.topMargin = getContext().getResources().getDimensionPixelSize(R.dimen.head_height);
        }
    }

    public void hide() {
        mTickCount = -1;
        setVisibility(GONE);
    }
}
